package com.zeyi.blog.social.github;

import com.zeyi.blog.handler.MyAuthenticationFailureHandler;
import com.zeyi.blog.handler.MyAuthenticationSuccessHandler;
import com.zeyi.blog.service.UserService;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author 黎先森
 */
@Configuration
public class GithubAuthConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Resource
    MyAuthenticationSuccessHandler successHandler;

    @Resource
    MyAuthenticationFailureHandler failureHandler;

    @Resource
    UserService userService;

    @Resource
    RestTemplate restTemplate;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        GithubAuthFilter githubAuthFilter = new GithubAuthFilter(restTemplate);
        githubAuthFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        githubAuthFilter.setAuthenticationSuccessHandler(successHandler);
        githubAuthFilter.setAuthenticationFailureHandler(failureHandler);

        http.authenticationProvider(new GithubAuthProvider(userService))
                .addFilterBefore(githubAuthFilter, AbstractPreAuthenticatedProcessingFilter.class);
    }
}
